<template>
  <div class="during-class-page">
    <div class="during-class-topping">
      <n-button type="primary" @click="dialogTap({ name: 'finish' })">
        <template #icon>
          <n-icon size="22">
            <Power />
          </n-icon>
        </template>
        结课
      </n-button>
      <div class="date">{{formatNowDate}}</div>
    </div>
    <div class="tool-wrap">
<!--      <div class="tool-wrap-left">-->
<!--        <n-popselect v-model:value="value" :options="options" trigger="click">-->
<!--          <div class="filter-item">-->
<!--            <div class="label">{{ value || '弹出选择' }}</div>-->
<!--            <n-icon size="20">-->
<!--              <ChevronDownOutline />-->
<!--            </n-icon>-->
<!--          </div>-->
<!--        </n-popselect>-->
<!--      </div>-->
      <div class="tool-wrap-middle">
        <div class="tab-wrap">
          <div class="tab-item" :class="{ active: tabType === 1 }" @click="tabType = 1">统计</div>
          <div class="tab-item" :class="{ active: tabType === 2 }" @click="tabType = 2">分析</div>
        </div>
      </div>
      <div class="tool-wrap-right">
        <div class="btn-item" @click="toolBtnTap('pen')">
          <img src="@/assets/img/duringClass/pen.png" alt="智能笔管理" />
          <div class="label">智能笔管理</div>
        </div>
        <div class="btn-item" @click="toolBtnTap('book')">
          <img src="@/assets/img/duringClass/pen.png" alt="课程教材" />
          <div class="label">课程教材</div>
        </div>
        <div class="btn-item" @click="toolBtnTap('integral')">
          <img src="@/assets/img/duringClass/pen.png" alt="奖励积分" />
          <div class="label">奖励积分</div>
        </div>
      </div>
    </div>
    <div class="statistics-wrap">
      <div class="statistics-item">
        <img src="@/assets/img/classroom/time.png" alt="课程时长" />
        <div class="label">课程时长 {{countDownTime}}</div>
      </div>
      <div class="statistics-item">
        <img src="@/assets/img/classroom/people.png" alt="参与学生数" />
        <div class="label">参与学生数 {{ realTimePeopleNum }}人</div>
      </div>
      <div class="statistics-item">
        <img src="@/assets/img/classroom/finish.png" alt="完成情况" />
        <div class="label">完成情况 {{ realTimeWordNumData.complete }}/{{ realTimeWordNumData.total }}</div>
      </div>
      <div class="statistics-item">
        <img src="@/assets/img/classroom/star.png" alt="综合表现" />
        <div class="label" style="margin-right: 24px">综合表现</div>
        <img src="@/assets/img/classroom/excellent.png" alt="优秀" />
        <div class="label" style="margin-right: 16px">X {{ realTimeWordNumData.scope3 }}</div>
        <img src="@/assets/img/classroom/good.png" alt="良好" />
        <div class="label" style="margin-right: 16px">X {{ realTimeWordNumData.scope2 }}</div>
        <img src="@/assets/img/classroom/commonly.png" alt="一般" />
        <div class="label">X {{ realTimeWordNumData.scope1 }}</div>
      </div>
    </div>
    <n-scrollbar style="height: calc(100% - 180px)">
      <div class="student-wrap" v-show="tabType === 1">
        <studentRadarItem v-for="(item, key, i) in realTimeData" :key="item.studentId" :studentInfo="item.studentInfo" :averageScore="item.averageScore" :wordNum="item.wordNum" :scoreIcon="item.scoreIcon" :radarData="item.radarData" :index="i" @click="dialogTap({ name: 'see', detail: item })" />
      </div>
      <div class="analysis-warp" v-show="tabType === 2">
        <studentAnalysisItem v-for="(item, key, i) in realTimeData" :key="item.studentId" :studentInfo="item.studentInfo" :wordNum="item.wordNum" :scoreIcon="item.scoreIcon" :wordData="item.wordData" @click="dialogTap({ name: 'see', detail: item })" />
      </div>
    </n-scrollbar>
    <transition
      name="fade-top"
    >
      <seeStudentHandwritingDrawer
        v-if="dialogState.visible && dialogState.name === 'see'"
        ref="seeStudentHandwritingDrawerRef"
        :init-select-item="dialogState.detail"
        :real-time-data="realTimeData"
        @close="dialogClose"
      />
    </transition>
    <transition
      name="fade-top"
    >
      <finishCourseDrawer
        v-if="dialogState.visible && dialogState.name === 'finish'"
        :realTimePeopleNum="realTimePeopleNum"
        :realTimeSortData="realTimeSortData"
        :realTimeDescSortData="realTimeDescSortData"
        :realTimeSortStudentData="realTimeSortStudentData"
        :realTimeWordNumData="realTimeWordNumData"
        :realTimeCourseAverageScore="realTimeCourseAverageScore"
        :countDownTime="countDownTime"
        @confirm="finishCourseTap"
        @close="dialogClose"
      />
    </transition>
  </div>
</template>

<script setup lang="ts">
  import { ChevronDownOutline, Power } from '@vicons/ionicons5';
  import {ref, reactive, computed, onUnmounted, onMounted} from 'vue';
  import { finishCourseAndSubmitData } from '@/api/dashboard';
  import { useDataTable } from '@/hooks/useDataTable';
  import studentRadarItem from '@/views/components/studentRadarItem/index.vue';
  import studentAnalysisItem from './components/studentAnalysisItem.vue';
  import seeStudentHandwritingDrawer from './components/seeStudentHandwritingDrawer.vue';
  import finishCourseDrawer from './components/finishCourseDrawer.vue';
  import { routerBack } from '@/utils';
  import {useCourse} from "@/store/modules/course";
  import {useIndexedDB} from "@/store/modules/indexedDB";
  import {format, differenceInSeconds} from "date-fns";
  import pointWorker from "./worker/point.worker?worker";
  import { actionSqliteData, saveImageToLocal, saveSqliteData } from "@/utils/ipcRenderer";
  import localforage from 'localforage';
  import * as constants from "@/config/constants";
  import { websiteConfig } from "@/config/website.config";

  const { dialogTap, dialogState, dialogClose, router } = useDataTable();
  const tabType = ref(1);
  const value = ref('1');
  const options = reactive([
    {
      label: '全部',
      value: '1',
    },
    {
      label: '一号',
      value: '2',
    },
    {
      label: '二号',
      value: '3',
    },
    {
      label: '三号',
      value: '4',
    },
  ]);

  const formatNowDate = ref(format(new Date(), 'yyyy年MM月dd日'))

  const currentCourseData = computed(() => {
    return useCourse().getCurrentCourseData;
  })
  const countDownTime = ref('')
  const interval = setInterval(() => {
    const now = new Date();
    const diff = differenceInSeconds(now, currentCourseData.value.courseStartTime);
    //获取还剩多少分钟
    const minute = parseInt(diff / 60 % 60);
    //获取还剩多少秒
    const second = diff % 60;
    countDownTime.value = (minute < 10 ? ('0' + minute) : minute) + ':' + (second < 10 ? ('0' + second) : second);
  }, 1000);
  // const matchingPenData = computed(() => {
  //   return useCourse().getCoursePenData.filter((item) => item.studentInfo);
  // });
  function toolBtnTap(type) {
    if (type === 'pen') {
      // routerBack();
      useCourse().setPageRoute('matching')
    } else {
      window['$message'].info('更多功能 开发中敬请期待');
    }
  }
  const seeStudentHandwritingDrawerRef = ref<any>(null);
  function finishCourseTap() {
    window['$dialog'].warning({
      title: '警告',
      content: '是否结束课程？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        try {
          await finishCourseAndSubmitData({
            studentExercises: realSubmitData.value
          });
          await saveSqliteData({
            action: 'del',
            delete_name: useCourse().getCurrentCourseData.courseId
          })
          await useIndexedDB().clearPointDB()
          await useCourse().setPageRoute('dashboard')
        } catch (e) {
          console.log(e);
        }
      },
    });
  }

  const realTimeData = ref({})
  const realTimeWordNumData = ref({
    total: 0,
    complete: 0,
    scope1: 0,
    scope2: 0,
    scope3: 0,
  });
  const realTimePeopleNum = ref(0)
  const realTimeSortData = ref([])
  const realTimeDescSortData = ref([])
  const realTimeSortStudentData = ref([])
  const realTimeCourseAverageScore = ref(0)
  const realSubmitData = ref([])
  const worker = new pointWorker();

  worker.onmessage = (e) => {
    try {
      const { data: { command, data } } = e;
      switch (command) {
        case 'returnData':
          realTimeData.value = data.resultMap;
          realTimeWordNumData.value = data.wordNum;
          realTimePeopleNum.value = data.realTimePeopleNum;
          realTimeSortData.value = data.sortData;
          realTimeDescSortData.value = data.sortDescData
          realTimeSortStudentData.value = data.sortStudentData
          realTimeCourseAverageScore.value = data.courseAverageScore
          realSubmitData.value = data.submitData
          seeStudentHandwritingDrawerRef.value?.refreshData()
          // console.log(data)
          setTimeout(() => {
            getPointData()
          }, 1000)
          break;
      }
    } catch (e) {
      console.log(e);
    }
  };
  const integralSettingData = reactive(useCourse().getIntegralSettingData)
  async function getPointData (){
    try {
      const res: any = await actionSqliteData({
        action: 'get-course-all-data',
        search_params: {
          courseId: useCourse().getCurrentCourseData.courseId,
        }
      })
      const matchingPenData = reactive(useCourse().getCoursePenData.filter((item) => item.studentInfo))
      worker.postMessage(
        {
          command: 'parsingData',
          data: {
            listData: res.result,
            courseId: useCourse().getCurrentCourseData.courseId,
            integralSettingData: JSON.parse(JSON.stringify(integralSettingData)),
            matchingPenData: JSON.parse(JSON.stringify(matchingPenData))
          },
        },
      );
    } catch (e) {
      console.log(e)
    }
  }

  onMounted(() => {
    getPointData()
  })
  onUnmounted(() => {
    clearInterval(interval)
    worker.terminate()
  })
</script>

<style scoped lang="less">
  .during-class-page {
    height: 100%;
  }
  .during-class-topping {
    display: flex;
    align-items: center;
    font-size: 24px;
    line-height: 36px;
    position: fixed;
    top: 60px;
    left: 36px;
    .n-button {
      margin-right: 12px;
      height: 36px;
      border-radius: 6px;
      font-size: 20px;
    }
  }
  .tool-wrap {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 36px;
    > div {
      width: 50%;
      flex: 1;
    }
    .tool-wrap-left {
      display: flex;
      align-items: center;
    }
    .filter-item {
      display: flex;
      align-items: center;
      font-size: 24px;
      margin-right: 36px;
      cursor: pointer;
      .label {
        margin-right: 6px;
      }
    }
    .tool-wrap-middle {
      display: flex;
      align-items: center;
      justify-content: center;
      position: absolute;
      width: 200px;
      left: 50%;
      margin-left: -100px;
    }
    .tab-wrap {
      width: 210px;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #fff;
      border-radius: 12px;
      .tab-item {
        width: 96px;
        height: 48px;
        border-radius: 9px;
        cursor: pointer;
        text-align: center;
        line-height: 48px;
        font-size: 24px;
        &.active {
          background-color: #eb6100;
          color: #fff;
        }
      }
    }
    .tool-wrap-right {
      display: flex;
      justify-content: flex-end;
      .btn-item {
        height: 60px;
        padding: 0 12px;
        display: flex;
        align-items: center;
        background-color: #fff;
        margin-left: 18px;
        font-size: 21px;
        border-radius: 12px;
        cursor: pointer;
        img {
          width: 24px;
          height: 24px;
          margin-right: 6px;
        }
      }
    }
  }
  .statistics-wrap {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(90deg, #fef2e9 0%, #fae0cd 100%);
    border-radius: 12px;
    margin-bottom: 24px;
    padding: 16px 0;
    .statistics-item {
      width: 25%;
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      border-right: 2px solid #e5c9b4;
      &:last-child {
        border-right: 0;
      }
      img {
        width: 28px;
        height: 28px;
        margin-right: 6px;
      }
      .label {
        font-size: 24px;
      }
    }
  }
  .student-wrap {
    display: flex;
    flex-wrap: wrap;
    //justify-content: space-between;
    .student-item {
      width: 450px;
      margin-right: 16px;
      border: 0;
      &:nth-child(4n + 4) {
        margin-right: 0;
      }
    }
  }
</style>
